package cn.com.ejiakanghu.service;

import afu.org.checkerframework.checker.igj.qual.I;
import cn.com.ejiakanghu.core.config.DirectExchangeRabbitMQConfig;
import cn.com.ejiakanghu.dto.PackageDto;
import cn.ejiakanghu.logistics.service.impl.LogisticBusiBaseServiceImpl;
import cn.ejiakanghu.logistics.service.impl.OrderStateService;
import cn.ejiakanghu.logistics.vo.StoreDeliveryModeEnum;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.linlinjava.litemall.core.lock_rfid.LockRfidUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.logistics.LogisticsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.AgedmallLgBaseInfoService;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.wechat.ToLitemallBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wj
 * @date 2022/1/25 14:37
 */
@Service
public class RfidService {

    private Logger logger = LoggerFactory.getLogger(RfidService.class);

    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;

    @Resource
    private LitemallOrderMapper litemallOrderMapper;

    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;

    @Resource
    private LogisticsMapper logisticsMapper;

    @Resource
    private LockRfidUtil lockRfidUtil;

    @Resource
    private AgedmallRfidGoodsProductMapper agedmallRfidGoodsProductMapper;

    @Resource
    private AgedmallCabinetGoodsMapper agedmallCabinetGoodsMapper;

    @Resource
    private AgedmallGoodsEquMapper agedmallGoodsEquMapper;

    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;

    @Resource
    private LeaseOrderService leaseOrderService;


    @Resource
    private OrderStateService orderStateService;

    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;

    @Resource
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;

    @Resource
    private AgedmallLgGoodsSignForRecordMapper agedmallLgGoodsSignForRecordMapper;

    @Resource
    private LogisticsGoodsUtil logisticsGoodsUtil;

    @Resource
    private AgedmallLgBaseInfoService agedmallLgBaseInfoService;

    @Resource
    private EnterpriseWeChatService enterpriseWeChatService;

    @Resource
    private AgedmallLgMissionManRecordMapper agedmallLgMissionManRecordMapper;






    /**
     * 触发修改rfid状态
     * @Param type 1-软链锁归还 2-医柜锁归还
     * @Param changeType 0-归还完成稿触发修改
     */
    public void changeRfidReturn(String rfidList,Integer type,Integer changeType){
        if(type==2){
            AgedmallRfidGoodsProductExample goodsProductExample=new AgedmallRfidGoodsProductExample();
            goodsProductExample.or().andRfidEqualTo(rfidList);
            AgedmallRfidGoodsProduct list = agedmallRfidGoodsProductMapper.selectOneByExample(goodsProductExample);
            AgedmallRfidGoodsProduct rfidGoodsProduct=new AgedmallRfidGoodsProduct();



            AgedmallCabinetGoodsExample cabinetGoodsExample=new AgedmallCabinetGoodsExample();
            cabinetGoodsExample.or().andGoodsRfidIdEqualTo(list.getId());
            AgedmallCabinetGoods cabinetGoods=new AgedmallCabinetGoods();



            AgedmallLgRfidGoodsCurStatExample goodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
            goodsCurStatExample.or().andTypeEqualTo(2).andRfidEqualTo(rfidList);
            AgedmallLgRfidGoodsCurStat goodsCurStat=new AgedmallLgRfidGoodsCurStat();

            switch (changeType){
                case 0:
                    rfidGoodsProduct.setStat(2);
                    cabinetGoods.setStat(6);
                    goodsCurStat.setCurStat(11);
                    break;
                default:
                    break;
            }

            agedmallRfidGoodsProductMapper.updateByExampleSelective(rfidGoodsProduct,goodsProductExample);
            agedmallCabinetGoodsMapper.updateByExampleSelective(cabinetGoods,cabinetGoodsExample);
            agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(goodsCurStat,goodsCurStatExample);
        }
        else {
            //首先判断是否是归还
            boolean returnGoods = isReturnGoods(rfidList);
            if(returnGoods){
                logger.info("是归还rfid:{}",rfidList);
            }

            //因为是租赁系统，首先判断是不是系统需要更改的rfid
            AgedmallLgRfidGoodsCurStatExample goodsCurStatExample=new AgedmallLgRfidGoodsCurStatExample();
            goodsCurStatExample.or().andTypeEqualTo(1).andRfidEqualTo(rfidList);
            AgedmallLgRfidGoodsCurStat curStat = agedmallLgRfidGoodsCurStatMapper.selectOneByExample(goodsCurStatExample);
            if(ObjectUtil.isNotNull(curStat)&&(curStat.getCurStat()==2||curStat.getCurStat()==3||curStat.getCurStat()==4||curStat.getCurStat()==5
                    ||curStat.getCurStat()==11)){
                logger.info("围老rfid:{}",rfidList);
                AgedmallGoodsEquExample goodsEquExample=new AgedmallGoodsEquExample();
                goodsEquExample.or().andTypeEqualTo(0).andEquIdEqualTo(Long.parseLong(rfidList)).andDeletedEqualTo((byte)0);
                AgedmallGoodsEqu goodsEqu=new AgedmallGoodsEqu();


                switch (curStat.getCurStat()){
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                        goodsEqu.setState(2);
                        goodsEqu.setDistributionType(3);
                        curStat.setCurStat(11);
                        break;
                    case 11:
                        goodsEqu.setDistributionType(3);
                    default:
                        break;
                }


                agedmallGoodsEquMapper.updateByExampleSelective(goodsEqu,goodsEquExample);
                agedmallLgRfidGoodsCurStatMapper.updateByPrimaryKeySelective(curStat);
            }

        }
    }

    /**
     *  判断当前插入桩上的是否是归还
     * @param rfidList
     * @return
     */
    public boolean isReturnGoods(String rfidList){
        LitemallOrderGoodsExample orderGoodsExample=new LitemallOrderGoodsExample();
        orderGoodsExample.setOrderByClause("add_time DESC");
        orderGoodsExample.createCriteria().andRfidEqualTo(rfidList).andStockTypeEqualTo(1);
        LitemallOrderGoods orderGoods = litemallOrderGoodsMapper.selectOneByExampleSelective(orderGoodsExample);
        if(orderGoods!=null){
            List<Integer> orderGoodsIds=new ArrayList<>();
            orderGoodsIds.add(orderGoods.getId());
            LitemallOrderItem orderItem = litemallOrderItemMapper.selectByPrimaryKey(orderGoods.getChildOrderId().intValue());
            LitemallOrder order= litemallOrderMapper.selectByPrimaryKey(orderItem.getParentId());
            if(orderItem.getOrderStatus().equals(OrderUtil.STATUS_LEASE_CONFIRM)){
                logger.info("归还子订单:{}",orderItem.getId());
                Integer baseInfoState = LgBaseInfoStatConstant.LEASE_BACK;

                //修改子订单状态
                orderItem.setOrderStatus(OrderUtil.STATUS_RETURN_SUCCESS);
                litemallOrderItemMapper.updateByPrimaryKeySelective(orderItem);

                //同步修改orderGoods状态
                orderStateService.modifyOrderGoodsStateBatch(orderGoodsIds, baseInfoState);

                //更新签收表
                for (int j = 0; j < orderGoodsIds.size(); j++) {
                    AgedmallLgGoodsSignForRecord goodsSignForRecord = new AgedmallLgGoodsSignForRecord();
                    goodsSignForRecord.setCreatedTime(LocalDateTime.now());
                    goodsSignForRecord.setLgBaseInfoId(null);
                    goodsSignForRecord.setState(1);
                    goodsSignForRecord.setGoodsId(orderGoodsIds.get(j).longValue());
                    goodsSignForRecord.setSignForTime(LocalDateTime.now());
                    goodsSignForRecord.setOrderCode(orderItem.getOrderCode());
                    goodsSignForRecord.setUserType(1);
                    agedmallLgGoodsSignForRecordMapper.insertSelective(goodsSignForRecord);
                }

                AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(orderItem.getStoreId().longValue());

                AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
                agedmallLgBaseInfo.setOrderCode(orderItem.getOrderCode()+"");
                agedmallLgBaseInfo.setLgType(LgBaseInfoLgType.MAINTAIN.getCode());
                agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(orderGoodsIds,null));
                agedmallLgBaseInfo.setUserName(order.getConsignee());
                agedmallLgBaseInfo.setPhone(order.getMobile());
                agedmallLgBaseInfo.setAddresss(order.getAddress());
                agedmallLgBaseInfo.setWarehouseType(0);
                agedmallLgBaseInfo.setNoticeType(1);
                agedmallLgBaseInfo.setWarehouseAddress(store.getAddressDetail());
                agedmallLgBaseInfo.setStoreId(store.getId().intValue());
                agedmallLgBaseInfo.setLgStat(LgBaseInfoStatConstant.UN_MAINTAINING);
                agedmallLgBaseInfo.setLgIsOver(0);
                agedmallLgBaseInfoService.add(agedmallLgBaseInfo);

                //企业微信
                //TODO 配送模式还不需要判断baseInfo李做的配置,
                int deliveryMode = store.getDeliveryMode();
                List<Integer> missionList=new ArrayList<>();
                if ((deliveryMode == StoreDeliveryModeEnum.SORT.getDeliveryMode() || deliveryMode == StoreDeliveryModeEnum.ALL.getDeliveryMode()) && !agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode())) {
                    //企业微信
                    missionList = logisticBusiBaseServiceImpl.createMission(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
                    //状态更新完成后调用企业微信进行维护抢单
                    if (missionList.isEmpty()) {
                        logger.error("归还完成调用企业微信抢单失败：{}", agedmallLgBaseInfo.getId());
                    } else {
                        missionList.forEach(missionId -> enterpriseWeChatService.sendNotice(missionId));
                    }
                }else if (deliveryMode == StoreDeliveryModeEnum.MANUAL.getDeliveryMode()){
                    missionList = logisticBusiBaseServiceImpl.createMissionBackstage(null, agedmallLgBaseInfo.getId().intValue(), LogisticsMissionTypeEnum.MAINTAIN.getCode());
                    AgedmallLgMissionManRecordExample agedmallLgMissionManRecordExample = new AgedmallLgMissionManRecordExample();
                    agedmallLgMissionManRecordExample.or().andBaseInfoIdEqualTo(agedmallLgBaseInfo.getId()).andMissionTypeEqualTo(LogisticsMissionTypeEnum.MAINTAIN.getCode());
                    //agedmallLgMissionManRecordExample.setOrderByClause("`id` DESC");
                    //未使用
                    //agedmallLgMissionManRecordExample.or().andIsUseEqualTo(0);
                    AgedmallLgMissionManRecord agedmallLgMissionManRecord = agedmallLgMissionManRecordMapper.selectOneByExampleSelective(agedmallLgMissionManRecordExample);
                    //接单
                    logisticBusiBaseServiceImpl.receiveOrderEvent(agedmallLgMissionManRecord.getManId().intValue(),missionList.get(0),null);
                    agedmallLgMissionManRecord.setIsUse(1);
                    //物流 -手动分配配货配送人员记录表 改为已使用状态
                    agedmallLgMissionManRecordMapper.updateByPrimaryKey(agedmallLgMissionManRecord);
                }

                //计算价格
                leaseOrderService.orderSettlement(orderItem.getOrderCode(), orderItem.getChildOrderCode());
                return true;
            }
        }
        return false;
    }

}
